<template>
  <section class='f-register'>
    <div class="f-cell">
      <p style="color: #848484">店铺类型</p>
      <van-radio-group v-model="form.shopType" direction="horizontal">
        <van-radio :name="1" icon-size="16px">个人店铺</van-radio>
        <van-radio :name="2" icon-size="16px" class="f-ml-20">企业店铺</van-radio>
      </van-radio-group>
    </div>
    <div class="f-cell f-mt-15">
      <p style="color: #848484">一键分销我的所有商品</p>
      <van-switch v-model="form.goodsCopyType" size="18px" active-value="1" inactive-value="0" />
    </div>

    <van-form class="f-mt-14" @submit="onSubmit" input-align="right" error-message-align="right">
      <van-cell-group>
        <van-field v-model="form.shopName" name="shopName" label="店铺名称" placeholder="请输入店铺名称"
          :rules="[{ required: true, message: '请填写店铺名称' }]" />

        <van-field v-model="form.shopUserName" name="shopUserName" label="店铺联系人" placeholder="请输入店铺联系人"
          :rules="[{ required: true, message: '请填写店铺联系人' }]" />

        <van-field v-model="form.certificateNumber" name="certificateNumber" label="联系人证件号" type="tel" placeholder="请输入联系人证件号"
          maxlength="18"
          :rules="[{ required: true, message: '请填写联系人证件号' },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请填写正确的证件号码'}]" />

        <van-field v-model="form.shopUserPhone" name="shopUserPhone" label="联系电话" placeholder="请输入联系电话" type="tel" maxlength="11"
          :rules="[{ required: true, message: '请填写联系电话' },{ pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号码'}]" />

        <van-field v-model="form.firstPassword" name="firstPassword" label="初始密码" placeholder="请输入初始密码"
          :type="form.showFirstPassword?'':'password'"
          :rules="[{ required: true, message: '设置初始密码' },{ validator: validatorPassword, message: firstPasswordMsg }]">
          <template #right-icon>
            <van-icon v-show="!form.showFirstPassword" name="closed-eye" @click="form.showFirstPassword = true" />
            <van-icon v-show="form.showFirstPassword" name="eye-o" @click="form.showFirstPassword = false" />
          </template>
        </van-field>
      </van-cell-group>

      <van-cell-group class="f-mt-14">
        <van-field v-model="form.promotionName" name="promotionName" label="客户经理" is-link readonly placeholder="请输入客户经理"
          @click="showPicker = true" />
        <van-field v-model="form.contactAddress" name="contactAddress" label="联系地址" placeholder="请输入联系地址" />
      </van-cell-group>

      <van-field v-if="form.shopType == 1" class="f-mt-14" name="idcardPhotoFront" label="文件上传"
        :rules="[{ required: true, message: '请上传联系人证件照片' }]">
        <template #label>
          <p>联系人证件照片</p>
          <p class="f-mt-05 f-fs-12 ">(身份证人像面)</p>
        </template>
        <template #input>
          <van-uploader v-model="form.idcardPhotoFront" :after-read="afterRead" :max-count="1" :preview-size="['167px', '104px']">
            <img class="f-img1" src="@/assets/imgs/jhh_datum_pic01.png" alt="">
          </van-uploader>
        </template>
      </van-field>

      <van-field v-if="form.shopType == 2" class="f-mt-14" v-model="form.companyName" name="企业名称" label="企业名称"
        placeholder="请输入企业名称" :rules="[{ required: true, message: '请填写企业名称' }]" />
      <van-field v-if="form.shopType == 2" name="licenseUrl" label="文件上传" :rules="[{ required: true, message: '请上传上传营业执照' }]">
        <template #label>
          <p>上传营业执照</p>
        </template>
        <template #input>
          <van-uploader v-model="form.licenseUrl" :after-read="afterRead1" :max-count="1" :preview-size="['167px', '104px']">
            <img class="f-img1" src="@/assets/imgs/jhh_btn_bl.png" alt="">
          </van-uploader>
        </template>
      </van-field>

      <van-field class="f-mt-14" name="shopSignboardPhoto" label="文件上传">
        <template #label>
          <p>商铺门头照片</p>
        </template>
        <template #input>
          <van-uploader v-model="form.shopSignboardPhoto" :after-read="afterRead2" :max-count="1"
            :preview-size="['167px', '104px']">
            <img class="f-img1" src="@/assets/imgs/jhh_datum_pic05.png" alt="">
          </van-uploader>
        </template>
      </van-field>

      <van-field class="f-mt-14" name="shopManagerPhoto" label="文件上传">
        <template #label>
          <p>商铺店长身份证照片</p>
        </template>
        <template #input>
          <van-uploader v-model="form.shopManagerPhoto" :after-read="afterRead3" :max-count="1"
            :preview-size="['167px', '104px']">
            <img class="f-img1" src="@/assets/imgs/jhh_datum_pic05.png" alt="">
          </van-uploader>
        </template>
      </van-field>

      <div class="f-tips">
        <p>温馨提示：</p>
        <p>1、联系电话请确保真实有效，将作为代注册商户登录淏咖宝平台的账号；</p>
        <p>2、联系人姓名与证件号务必与支付宝认证账号的实名信息一致，否则将影响代注册商户的实名认证结果。</p>
      </div>

      <div class="f-submit-btn">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">选择客户经理</p>
      <van-picker ref="pickerRef" v-model="selectUserId" :columns="userList" :columns-field-names="customFieldName"
        :show-toolbar="false" />
      <div class="f-popup-btn">
        <van-button block type="primary" @click="handlePicker()">确定</van-button>
      </div>
    </van-popup>

  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from "vuex";
import api from '../api'
import { getStore, warningDeal } from '@/utils/utils';
import hexMD5 from "@/utils/md5.min.js"

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const pickerRef = ref()

    const state = reactive({
      form: {
        "certificateNumber": "",
        "companyName": "",
        "firstPassword": "",
        "idcardPhotoBack": "",
        "shopName": "",
        "shopType": 1,
        "shopUserName": "",
        "shopUserPhone": "",
        goodsCopyType: 0,
      },
      idcardPhotoFront: '',
      licenseUrl: '',
      shopSignboardPhoto: '',
      shopManagerPhoto: '',
      passwordMsg: '',

      showPicker: false,
      selectUserId: [],
      userList: [],
      customFieldName: {
        text: 'name',
        value: 'userId',
        children: 'children'
      },
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '商户代注册',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
      });

      getUserList()
    })

    const getUserList = () => {
      let json = {
        shopId: getStore('USER_INFO').companyId
      }
      api.userList(json).then(res => {
        state.userList = res.data
      })
    }

    const afterRead = (params) => {
      params.status = 'uploading';
      params.message = '上传中...';

      const formData = new FormData();
      formData.append("file", params.file) // 这里填入你的file文件对象

      api.uploadImg(formData).then(res => {
        params.status = 'done';
        state.idcardPhotoFront = res.data.ossUrl
      }).catch(err => {
        params.status = 'failed';
        params.message = '上传失败';
      })
    };

    const afterRead1 = (params) => {
      params.status = 'uploading';
      params.message = '上传中...';

      const formData = new FormData();
      formData.append("file", params.file) // 这里填入你的file文件对象

      api.uploadImg(formData).then(res => {
        params.status = 'done';
        state.licenseUrl = res.data.ossUrl
      }).catch(err => {
        params.status = 'failed';
        params.message = '上传失败';
      })
    };

    const afterRead2 = (params) => {
      params.status = 'uploading';
      params.message = '上传中...';

      const formData = new FormData();
      formData.append("file", params.file) // 这里填入你的file文件对象

      api.uploadImg(formData).then(res => {
        params.status = 'done';
        state.shopSignboardPhoto = res.data.ossUrl
      }).catch(err => {
        params.status = 'failed';
        params.message = '上传失败';
      })
    };

    const afterRead3 = (params) => {
      params.status = 'uploading';
      params.message = '上传中...';

      const formData = new FormData();
      formData.append("file", params.file) // 这里填入你的file文件对象

      api.uploadImg(formData).then(res => {
        params.status = 'done';
        state.shopManagerPhoto = res.data.ossUrl
      }).catch(err => {
        params.status = 'failed';
        params.message = '上传失败';
      })
    };

    const onSubmit = (values) => {
      let json = JSON.parse(JSON.stringify(state.form))
      json.idcardPhotoFront = state.idcardPhotoFront
      json.licenseUrl = state.licenseUrl
      json.shopSignboardPhoto = state.shopSignboardPhoto
      json.shopManagerPhoto = state.shopManagerPhoto
      json.firstPassword = hexMD5(json.firstPassword)
      api.registerProxy(json).then(res => {
        pageJump('registerSuccess', res.data)
      })
    };

    const pageJump = (name, params) => {
      router.replace({
        path: `/shop/${name}`,
        query: {
          shopName: params.shopName,
          contactsName: params.contactsName,
          loginAccount: params.loginAccount,
          firstPassword: state.form.firstPassword,
          certificateNumber: state.form.certificateNumber,
          shopId: params.shopId,
        }
      })
    }

    const validatorPassword = (val) =>
      new Promise((resolve) => {
        const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/;
        if (reg.test(val)) {
          resolve(true)
        } else {
          state.passwordMsg = '密码长度8位以上,由大写字母、小写字母、数字、特殊符号中两种以上方式组成'
          resolve(false)
        }
      });

    const firstPasswordMsg = (value, rule) => {
      return state.passwordMsg
    }

    const handlePicker = (e) => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      state.form.promotionName = data.name
      state.form.promotionId = data.userId
      state.showPicker = false
    }

    return {
      ...toRefs(state),
      pickerRef,
      afterRead,
      afterRead1,
      afterRead2,
      afterRead3,
      onSubmit,
      pageJump,
      validatorPassword,
      firstPasswordMsg,
      handlePicker
    }
  }
}
</script>
<style lang='scss' scoped>
.f-register {
  .f-cell {
    width: 375px;
    height: 53px;
    background: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding: 20px 15px;
  }
  .f-mt-14 {
    margin-top: 14px;
  }
  .f-tips {
    padding: 7px 14px;
    font-size: 10px;
    color: #ff2b2b;
  }
  .f-submit-btn {
    margin-top: 70px;
    margin-bottom: 30px;
    padding: 0 62px;
  }
  .f-img1 {
    width: 167px;
    height: 104px;
  }
}
</style>